import time
from airtest.core.api import connect_device, snapshot
import subprocess

def start_weibo():
    try:
        result = subprocess.run(["tidevice", "launch", "com.sina.weibo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode == 0:
            print("微博启动成功")
        else:
            print("微博启动失败:", result.stderr.decode())
    except Exception as e:
        print(f"启动微博时发生错误: {e}")

def stop_weibo():
    try:
        result = subprocess.run(["tidevice", "kill", "com.sina.weibo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode == 0:
            print("微博退出成功")
        else:
            print("微博退出失败:", result.stderr.decode())
    except Exception as e:
        print(f"退出微博时发生错误: {e}")

def start_wda(port=8200):
    try:
        result = subprocess.Popen(["tidevice", "wdaproxy", "-B", "com.binmin.WebDriverAgentRunner", "--port", str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        time.sleep(5)  # 等待WDA启动
        print(f"WDA启动成功，端口 {port}")
    except Exception as e:
        print(f"启动WDA时发生错误: {e}")
        raise

def main():
    port = 8200  # 你想要使用的新端口
    try:
        start_wda(port)
        print("连接设备中...")
        connect_device(f"iOS:///127.0.0.1:{port}")
        print("设备连接成功")
        start_weibo()
        time.sleep(20)  # 等待20秒
        snapshot(filename="weibo_screenshot.png")
        print("截图已保存")
    except Exception as e:
        print(f"执行过程中发生错误: {e}")
    finally:
        stop_weibo()

if __name__ == "__main__":
    main()